'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【checkTaskStatus】检查任务状态:', event);
  
  const { publisherId } = event;
  
  try {
    // 1. 查找发布者的所有任务
    const tasksRes = await db.collection('taskList')
      .where({ publisher_id: publisherId })
      .orderBy('publish_time', 'desc')
      .limit(10)
      .get();
    
    console.log('【checkTaskStatus】任务列表:', tasksRes.data);
    
    // 2. 查找发布者的所有收入记录
    const incomeRes = await db.collection('task_income_records')
      .where({ publisher_id: publisherId })
      .orderBy('create_time', 'desc')
      .limit(10)
      .get();
    
    console.log('【checkTaskStatus】收入记录列表:', incomeRes.data);
    
    // 3. 分析任务状态
    const taskAnalysis = tasksRes.data.map(task => {
      const hasReceiver = task.receiver_id && task.receiver_id !== task.publisher_id;
      const hasIncomeRecord = incomeRes.data.some(record => 
        record.task_id === task._id || record.publisher_id === task.publisher_id
      );
      
      return {
        id: task._id,
        title: task.title,
        status: task.status,
        publisher_id: task.publisher_id,
        receiver_id: task.receiver_id,
        receiver_name: task.receiver_name,
        hasReceiver: hasReceiver,
        hasIncomeRecord: hasIncomeRecord,
        reward: task.reward
      };
    });
    
    return {
      code: 200,
      msg: '检查完成',
      data: {
        publisherId,
        tasks: taskAnalysis,
        incomeRecords: incomeRes.data.map(record => ({
          id: record._id,
          task_id: record.task_id,
          publisher_id: record.publisher_id,
          receiver_id: record.receiver_id,
          reward_amount: record.reward_amount,
          status: record.status,
          create_time: record.create_time,
          complete_time: record.complete_time
        }))
      }
    };
    
  } catch (error) {
    console.error('【checkTaskStatus】检查失败:', error);
    return {
      code: 500,
      msg: '检查失败',
      error: error.message
    };
  }
};